package main

import (
	"fmt"
	"log"
	"net"
	"os"
)

func main() {
	unixSocket := NewUnixSocket("./domainsocket")
	unixSocket.Serv()
}

type UnixSocket struct {
	fileName string
	bufSize  int
	handler  func(string) string
}

func NewUnixSocket(fileName string, size ...int) *UnixSocket {
	size1 := 10480
	if size != nil {
		size1 = size[0]
	}

	return &UnixSocket{fileName: fileName, bufSize: size1}
}

func (this *UnixSocket) Serv() {
	os.Remove(this.fileName)

	//这一步将创建unix套接字和绑定一起做了
	addr, err := net.ResolveUnixAddr("unix", this.fileName)
	if err != nil {
		panic(err)
	}

	lister, err := net.ListenUnix("unix", addr)
	if err != nil {
		panic(err)
	}
	defer lister.Close()

	fmt.Println("listening on ", lister.Addr())

	//循环监听消息的到来
	for {
		c, err := lister.Accept()
		if err != nil {
			panic(err)
		}

		go this.HandleServerConn(c)
	}

}

//接收连接并进行处理
func (this *UnixSocket) HandleServerConn(c net.Conn) {
	defer c.Close()
	buf := make([]byte, this.bufSize)
	nr, err := c.Read(buf)
	if err != nil {
		log.Println(err)
	}

	result := this.HandleServerContext(string(buf[0:nr]))
	if _, err = c.Write([]byte(result)); err != nil {
		log.Println(err)
	}

}

func (this *UnixSocket) SetContextHandler(f func(string) string) {
	this.handler = f
}

func (this *UnixSocket) HandleServerContext(context string) string {
	if this.handler != nil {
		return this.handler(context)
	}
	return context
}
